/*
 * $Id: search.c,v 1.2 2005-12-11 15:49:11 bacon Exp $
 */

#include <xp/bas/search.h>

void* xp_bsearch (
	const void *key, const void *base, xp_size_t nmemb, 
	xp_size_t size, void* arg, xp_search_compare_t compar)
{
	int n;
	const void* mid;
	xp_size_t lim;

	for (lim = nmemb; lim > 0; lim >>= 1) {
		mid = ((xp_byte_t*)base) + (lim >> 1) * size;

		n = (compar) (key, mid, arg); 
		if (n == 0) return (void*)mid;
		if (n > 0) { base = ((const xp_byte_t*)mid) + size; lim--; }
	}

	return XP_NULL;
}

void* xp_lsearch (
	const void* key, const void* base, xp_size_t nmemb,
	xp_size_t size, void* arg, xp_search_compare_t compar)
{
	while (nmemb > 0) {
		if (compar(key, base, arg) == 0) return (void*)base;
		base = ((const xp_byte_t*)base) + size;
		nmemb--;
	}
	return XP_NULL;
}

